package com.za.plugin.transfer.func;


import com.za.plugin.pojo.Content;
import com.za.plugin.util.StrUtil;

//   把 group_concat()  函数替换为 wm_concat() 函数 ,
// GROUP_CONCAT(bus.biz_category_name SEPARATOR '、') => wm_concat( bus.biz_category_name )
public class GroupConcatFunctionTransfer implements FunctionTransfer {
    @Override
    public boolean isSupport(String sql) {
        return sql.toLowerCase().contains("group_concat");
    }
    @Override
    public String transfer(String sql) {
        sql=sql.toLowerCase();
        if (sql.contains("group_concat")) {
            int idx = sql.indexOf("group_concat");
            while (idx >= 0) {
                int left = sql.indexOf('(', idx);
                Content contentObj = StrUtil.getExpectContent(sql, left);
                String content = contentObj.getExpectStr().trim();
                int end = contentObj.getEnd();
                content = content.trim().replaceAll("\\s*\\(\\s*", "\\(").replaceAll("\\s*\\)\\s*", "\\)")
                        .replaceAll("\\s*\\.\\s*", ".").replaceAll("\\s*\\,\\s*", "\\,");
                String[] splitArr = content.split("\\s+");


                // group_concat(distinct xx order by yy separator 'zz')
                if (content.contains("distinct ")) {
                    if(content.contains(" case when ")){
                        int startIdx = content.indexOf("case when ");
                        int endIdx = content.lastIndexOf(" end");
                        String ele = content.substring(startIdx, endIdx + 4);
                        sql = sql.substring(0, idx) + " wm_concat(distinct " + ele + ") " + sql.substring(end);
                    }else{
                        sql = sql.substring(0, idx) + " wm_concat(distinct " + splitArr[1] + ") " + sql.substring(end);
                    }
                } else {
                    sql = sql.substring(0, idx) + " wm_concat(" + splitArr[0] + ") " + sql.substring(end);
                }
                idx = sql.indexOf("group_concat", left);
            }
        }
        return sql;
    }
}
